<template>
  <base-modal :title="$t('customer.batchRemindingCustomerDialog.title.create')" :show.sync="batchRemindingCustomerDialog" width="500px" class="batch-remind-customer-dialog" @closed="reset">
    <el-form label-width="80px" ref="form" :model="form" >

      <el-form-item :label="$t('customer.batchRemindingCustomerDialog.form.remind.label')">
        <el-select v-model="form.remindId" :placeholder="$t('customer.batchRemindingCustomerDialog.form.remind.placeholder')" @change="defaultUserOfDifferentSelectedRemind">
          <el-option v-for="item in remindTemplate" :label="item.name" :value="item.id" :key="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-show="selectedRemind.sendWay !== 1" :label="$t('customer.batchRemindingCustomerDialog.form.remindContent.label')" class="content-item">
        {{selectedRemind.content}}
      </el-form-item>
      <el-form-item :label="$t('customer.batchRemindingCustomerDialog.form.remindRule.label')">
        {{remindRule}}
      </el-form-item>
      <el-form-item v-show="selectedRemind.sendWay === 1 && !selectedRemind.isDdResponse" :label="$t('common.bizComponents.bizSendEmail.label.subject')">
        {{selectedRemind.emailTitle}}
      </el-form-item>
      <el-form-item v-show="selectedRemind.sendWay === 1 && !selectedRemind.isDdResponse" :label="$t('common.base.emailContent')" class="content-item">
        {{selectedRemind.emailContent}}
      </el-form-item>
      <el-form-item :label="$t('customer.batchRemindingCustomerDialog.form.user.label')" prop="users">
        <template v-if="selectedRemind.isDdResponse">
          
          <base-select-user-input
            class="base-select-user-input-item"
            :placeholder="$t('customer.batchRemindingCustomerDialog.form.user.label')"
            multiple 
            :collapse="false"
            :error="error"
            v-model="form.users" 
            @input="validateUser"
          >
          </base-select-user-input>
          
          <!-- <base-select
            v-model="form.users"
            :remote-method="searchManager"
            @input="validateUser"
            multiple
            :error="error"
            is-use-value
            placeholder="请选择通知人"
          >
            <template slot="option" slot-scope="{option}">
              <div class="initiator-option-row">
                <template v-if="isOpenData">
                  <open-data type='userName' :openid="option.value || option.staffId"></open-data>
                </template>
                <template v-else>
                  <span class="initiator-display-name">{{option.label}}</span>
                </template>
              </div>
            </template>
          </base-select> -->
          
          <span style="display: inline-block; margin-top: 10px;">{{$t('customer.batchRemindingCustomerDialog.form.user.checkbox.label')}}：</span>
          <el-checkbox-group :value="sendRoleSetting" @input="change" style="display:inline">
            <el-checkbox label="sendToCustomerExecutor">{{$t('customer.batchRemindingCustomerDialog.form.user.checkbox.executor')}}</el-checkbox>
            <el-checkbox label="sendToCustomerTag">{{$t('customer.batchRemindingCustomerDialog.form.user.checkbox.tag')}}</el-checkbox>
          </el-checkbox-group>
        </template>
        <template v-else>
          <el-radio-group v-model="form.isAllLm">
            <el-radio :label="0" style="width: 120px">{{$t('customer.batchRemindingCustomerDialog.form.user.allCheckbox[0]')}}</el-radio>
            <el-radio :label="1" style="width: 120px">{{$t('customer.batchRemindingCustomerDialog.form.user.allCheckbox[1]')}}</el-radio>
          </el-radio-group>
        </template>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <remind-icon></remind-icon>
      <el-button @click="batchRemindingCustomerDialog = false">{{$t('common.base.cancel')}}</el-button>
      <el-button type="primary" @click="onSubmit" :disabled="pending">{{$t('common.base.confirm')}}</el-button>
    </div>
  </base-modal>
</template>

<script>
import { isOpenData } from '@src/util/platform';
import _ from 'lodash';
import RemindIcon from './RemindIcon.vue';
import i18n, {t} from '@src/locales'
import { getSettingRemindFieldList } from '@src/api/SettingApi'

export default {
  name: 'batch-reminding-customer-dialog',
  data: () => {
    return {
      isOpenData,
      sendRoleSetting: [],
      remindTemplate: [],
      remoteSearchCM: {
        loading: false,
        options: [],
      },
      form: {
        ids: '',
        isAllLm: 0,
        remindId: null,
        users: [],
      },
      batchRemindingCustomerDialog: false,
      pending: false,
      error: false,
      fieldList: [],
    }
  },
  props: {
    selectedIds: {
      type: Array,
      default: () => ([]),
    },
    modal: {
      required: true,
      type: String,
      validator: function(value) {
        return ['customer', 'product'].includes(value);
      }
    }
  },
  components: {
    RemindIcon
  }, 
  computed: {
    fieldNameMap() {
      return this.fieldList.reduce((acc, cur) => {
        acc[cur.fieldName] = cur.displayName;
        return acc;
      }, {})
    },
    selectedRemind() {
      return this.remindTemplate.filter(rt => rt.id === this.form.remindId)[0] || {};
    },
    remindRule() {
      // TODO 国际化 bell 时间
      let { isRepeat, period, fieldName, fieldDisplayName, isAhead, hours, periodUnit, timeUnit, } = this.selectedRemind;
      let unit = periodUnit === 'day' ? i18n.t('common.time.day') : (periodUnit === 'week' ? i18n.t('common.time.week'): i18n.t('common.time.month'));
      let isahead = isAhead ? i18n.t('common.base.before') : i18n.t('common.base.after');
      let dorh = (timeUnit == 'hour' || !timeUnit) ? i18n.t('common.time.hour') : i18n.t('common.time.day');
      
      const displayFieldName = this.fieldNameMap[fieldName]
      fieldDisplayName = displayFieldName || fieldDisplayName
      
      if (!isRepeat){
        if(fieldDisplayName){
          return i18n.t('common.bizComponents.bizBatchRemind.ruleTip.noRepeat', {
            name: fieldDisplayName,
            time: (isahead + hours) + dorh,
          })
          // return `单次通知：根据${fieldDisplayName + (isahead + hours) + dorh}提醒`;
        }
        return i18n.t('common.base.null')
      }
      if(period){
        return i18n.t('common.bizComponents.bizBatchRemind.ruleTip.repeat', {
          name: fieldDisplayName,
          time: (isahead + hours) + dorh,
          period: period + unit,
        })
        // return `重复通知：根据${fieldDisplayName + (isahead + hours) + dorh}，每${period + unit}发出提醒`;
      }
      return i18n.t('common.base.null')
    },
  },
  mounted() {
    this.getSettingRemindFieldList();
    this.fetchData();
  },
  methods: {
    change (val) {
      this.sendRoleSetting = val;
      this.validateUser();
    },
    initSelect (info) {
      this.sendRoleSetting = [];
      if (info && info.sendToCustomerExecutor) this.sendRoleSetting.push('sendToCustomerExecutor');
      if (info && info.sendToCustomerTag) {
        this.sendRoleSetting.push('sendToCustomerTag')
      }
    },
    reset() {
      this.form = {
        ids: '',
        isAllLm: 'n',
        remindId: null,
        users: []
      };
    },
    validateUser() {
      if (!this.selectedRemind.isDdResponse) return this.error = false;
      if ((!this.form.users || !this.form.users.length) && this.sendRoleSetting.length == 0) {
        // 内部提醒
        return this.error = true;
      }
      return this.error = false;
    },
    async onSubmit() {
      if (this.validateUser()) return;

      const params = this.buildParams();
      this.pending = true;
      this.$http.post('/scheduler/buildBatch', params)
        .then(res => {
          let ids = this.selectedIds;
          const actionName = this.$t('customer.batchRemindingCustomerDialog.onSubmit.actionName.add');
          if (res.status === 0) {
            this.$platform.alert(this.$t('customer.batchRemindingCustomerDialog.onSubmit.successMsg', {actionName}));
          }
          if (res.status === 1 && res.data) {
            this.$platform.alert(`${this.$t('customer.batchRemindingCustomerDialog.onSubmit.alreadyHaveMsg', {actionName})}：${res.data.join(',')}`);
          }
          if (res.status === 1 && !res.data) {
            this.$platform.alert(`${this.$t('customer.batchRemindingCustomerDialog.onSubmit.failMsg', {actionName})}${(res.data || res.message) && (`，${ res.data || res.message}`)}`);
          }
          this.batchRemindingCustomerDialog = false;
          this.pending = false;

          this.$emit('success-callback', ids);
        })
        .catch(err => {
          this.$platform.alert(this.$t('customer.batchRemindingCustomerDialog.onSubmit.failMsg', {actionName}));
          this.pending = false;
          console.error('post to /scheduler/buildBatch err', err)
        });
    },
    buildParams() {
      let params = {
        ids: this.selectedIds.join(','),
        remindId: this.form.remindId,
        sendRoleSetting: {},
      };

      if (this.selectedRemind.isDdResponse) {
        params.isAllLm = 0;
        params.users = this.form.users.map(({ label, value, phone, displayName, userId, staffId }) => {
          return { 
            name: label || displayName,  
            id: value || staffId || userId, 
            phone
          }
        })
      } else {
        params.isAllLm = this.form.isAllLm;
        params.users = [];
      }

      params.sendRoleSetting.sendToCustomerExecutor = this.sendRoleSetting.indexOf('sendToCustomerExecutor') != -1;
      params.sendRoleSetting.sendToCustomerTag = this.sendRoleSetting.indexOf('sendToCustomerTag') != -1;

      return params;
    },
    openBatchRemindingCustomerDialog() {
      if (!this.selectedIds.length) {
        return this.$platform.alert(this.$t('customer.batchRemindingCustomerDialog.openNoCustomer'));
      }
      this.form.remindId = (this.remindTemplate[0] || {}).id;
      this.batchRemindingCustomerDialog = true;
      this.defaultUserOfDifferentSelectedRemind();
    },
    defaultUserOfDifferentSelectedRemind() {
      let users = [];
      if (this.selectedRemind.isDdResponse) {
        users = this.selectedRemind.loginUserList || this.selectedRemind.users || [];
      }

      if (!this.selectedRemind.isDdResponse) {
        this.form.isAllLm = Number(!this.selectedRemind.isDefaultLinkman);
      }

      this.initSelect(this.selectedRemind.sendRoleSetting);
      this.form.users = _.cloneDeep(users).map(({ id, name, userId, displayName }) => ({ label: name || displayName, value: id || userId }))
    },
    fetchData() {
      this.$http.get('/customer/getReminds', {pageSize: 0, })
        .then(res => {
          if (!res || res.status) return;
          res.list = res.list || []
          this.remindTemplate = res.list
            .map(r => {
              r.name += `(${r.isDdResponse ? t('customer.batchRemindingCustomerDialog.remindTempName.in') : r.sendWay ? t('customer.batchRemindingCustomerDialog.remindTempName.outEmail') : t('customer.batchRemindingCustomerDialog.remindTempName.outSms')})`;
              return Object.freeze(r);
            });
        })
        .catch(err => console.error('err', err));
    },
    async getSettingRemindFieldList() {
      const params = {
        modal: this.modal
      }
      const result = await getSettingRemindFieldList(params)
      const fieldList = result || []
      this.fieldList = fieldList
    },
    searchManager(params) {
      // params has three properties include keyword、pageSize、pageNum.
      const pms = params || {};

      return this.$http.get('/customer/userTag/list', pms)
        .then(res => {
          if (!res || !res.list) return;
          if (res.list) {
            res.list = res.list.map(user => Object.freeze({
              label: user.displayName,
              value: user.staffId,
              phone: user.cellPhone,
            }))
          }

          return res;
        })
        .catch(e => console.log(e));
    },
  },
}
</script>

<style lang="scss">

  .batch-remind-customer-dialog {

    .el-select .el-select__tags>span {
      display: contents;
    }

    .base-modal-body {
      padding: 10px 30px 0;
    }

    .el-form-item {
      margin: 0;
    }
    .el-radio {
      line-height: 32px;
    }

    .el-select {
      width: 100%;
    }

    .content-item {
      .el-form-item__content {
        max-height: 200px;
        overflow-y: auto;
      }
    }

    .dialog-footer {
      display: flex;
      justify-content: flex-end;
    }
  }

</style>
